<?php

/**
 * This file is part of the Codizer package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright   Copyright (c) 2010 Advisa (http://www.advisa.fr)
 * @author      Codizer Core Team <team@codizer.org>
 * @package     Codizer
 */

class f_database_Dumper
{
	private static $instance;

    private $dumpDir;
	
	/**
	 * @return f_database_Dumper
	 */
	private function __construct()
	{
        $this->dumpDir = WEBAPP_DIR.DS."dumps";
		return $this;
	}
	
	/**
	 * Get singleton instance
	 *
	 * @return f_database_Dumper
	 */
	public static function getInstance()
	{
		if(self::$instance === null)
		{
			self::$instance = new self();
		}
		return self::$instance;
	}
	
	/**
	 * Dump the database from config file
	 *
	 */
	public function dumpDatabase()
	{
		$config = f_loader_Config::getInstance()->getParameters("DBConfig");

		if(!is_dir($this->dumpDir))
		{
			mkdir($this->dumpDir, 0777, true);
		}
		
		$dumpFileName = $this->dumpDir.DS.$config['dbName']."-".date("Ymd-His").".sql";
		
		echo COLOR_GREEN."Dumping".COLOR_NORMAL." -> Database dump in progress\n";
		
		$command = "mysqldump -h ".$config['host']." -u ".$config['login']." -p".$config['password']." -r".$dumpFileName." ".$config['dbName'];
		exec($command, $output, $returnvar);
		
		if($returnvar == 0)
		{
			echo COLOR_GREEN."Dumping".COLOR_NORMAL." -> Database dump is ok ($dumpFileName)\n";
		}
		else
		{
			echo COLOR_RED."Error".COLOR_NORMAL." -> Database dump has failed\n";
		}
	}
	
	/**
	 * Retrieve the dumps file list
	 *
	 * @return array
	 */
	public function getDumpsList()
	{		
		return f_file_Resolver::getInstance()->fromDirectory($this->dumpDir)->setMask("*.sql")->find();
	}
	
	/**
	 * Restore a dump file
	 *
	 * @param string $dumpFile
	 */
	public function restoreDump($dumpFile)
	{
		$config = f_loader_Config::getInstance()->getParameters("DBConfig");
		
		echo COLOR_GREEN."Restore".COLOR_NORMAL." -> Database restore in progress\n";
		
		$command = "mysql -u ".$config['login']." -p".$config['password']." --default-character-set=utf8 ".$config['dbName']." < ".$dumpFile;
		exec($command, $output, $returnvar);
		
		if($returnvar == 0)
		{
			echo COLOR_GREEN."Restore".COLOR_NORMAL." -> Database restore is ok\n";
		}
		else
		{
			echo COLOR_RED."Error".COLOR_NORMAL." -> Database restore has failed\n";
		}		
	}
}